package cn.com.zsc.system;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Vector;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.com.zsc.system.vo.CheckMenuTreeVO;
import cn.com.zsc.system.vo.ChildrenTreeVO;
import cn.com.zsc.system.vo.MenuTreeVO;
import cn.com.zsc.system.vo.UserVO;
import cn.com.zsc.util.Azdg;
import cn.com.zsc.util.ConstValue;

import com.jarp.db.DAO;

/**
 * 权限管理
 * @author 杨景
 *
 */
public class RoleManage {	
	/**
	 * 获取用户tree
	 */
	public String getUserTree() {
		ChildrenTreeVO ctreeVo = new ChildrenTreeVO();
		
		ctreeVo.setId("-1");
		ctreeVo.setText("用户");
		ctreeVo.setLeaf(false);
		ctreeVo.setChildren(getUserData());
		ctreeVo.setIconCls("folder");
		
		ArrayList<ChildrenTreeVO> userRoot = new ArrayList<ChildrenTreeVO>();
		userRoot.add(ctreeVo);
		
		JSONArray json = new JSONArray();
		json = JSONArray.fromObject(userRoot);
		
		return json.toString();
	}

	/**
	 * 获取用户数据
	 */
	@SuppressWarnings("unchecked")
	public String getUserData() {
		String sql = "select * from app_login";
		
		DAO dao = new DAO();
		Vector<Hashtable<String, String>> v = new Vector<Hashtable<String, String>>();
		
		String resultStr = "";
		
		try {
			v = dao.getDataSet(ConstValue.DBNAME, sql);
			
			if (v != null) {
				ArrayList<UserVO> list = new ArrayList<UserVO>();
				
				for (int i = 0; i < v.size(); i++) {
					Hashtable<String, String> table = (Hashtable<String, String>) v.get(i);
					UserVO user = new UserVO();
					
					user.setId(table.get("UID"));
					user.setText(table.get("UNAME"));
					user.setUid(Integer.parseInt(table.get("UID")));
					user.setUsername(table.get("UNAME"));
					user.setPassword(Azdg.decrypt(table.get("UPWD")));
					user.setName(table.get("NAME"));
					user.setRemarked(table.get("REMARKED"));
					user.setLeaf(true);
					
					list.add(user);
				}
				
				JSONArray json = new JSONArray();
				json = JSONArray.fromObject(list);
				resultStr = json.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ConstValue.EMPTY_RECORD_NOT_PAGEING;
		}
		
		return resultStr;
	}

	/**
	 * 获取菜单tree
	 */
	public String getMenuTree(String pid, String userID, String plCode) {
        // 先查最订层菜单
		String sql = "select * from cm_commlist where PL_CODE='"+plCode+"' and CL_PCODE="+pid;

		DAO dao = new DAO();
		Vector<Hashtable<String, String>> v = new Vector<Hashtable<String, String>>();
		
		ArrayList menuList = this.getUserMenuList(userID);
		
		String resultStr = "";

		try {
			v = dao.getDataSet(ConstValue.DBNAME, sql);
			
			if (v == null) {
				sql = "select * from cm_commlist where CL_PCODE=-1 and PARM=" + pid;
				v = dao.getDataSet(ConstValue.DBNAME, sql);
			}

			if (v != null) {
				ArrayList list = new ArrayList();

				for (int i = 0; i < v.size(); i++) {
					Hashtable<String, String> table = (Hashtable<String, String>)v.get(i);
					String currentCode = table.get("CL_CODE").toString();

					if (hasChild(currentCode, plCode)) {
						MenuTreeVO mtv = new MenuTreeVO();
						
						mtv.setId(table.get("CL_CODE").toString());
						mtv.setText(table.get("CL_NAME").toString());
						mtv.setLinkUrl(table.get("REMARKED").toString());
						mtv.setIsPageLink("1");
						mtv.setIconCls("folder");
						mtv.setLeaf(false);
						mtv.setChildren(table.get("REMARKED").toString());
						mtv.setChildren(getMenuTree(mtv.getId(), userID, table.get("PL_CODE").toString()));	
						
						list.add(mtv);
					} else {
						CheckMenuTreeVO ctv=new CheckMenuTreeVO();
						
						ctv.setId(table.get("CL_CODE").toString().trim());
						ctv.setText(table.get("CL_NAME").toString().trim());
						ctv.setLinkUrl(table.get("REMARKED").toString().trim());
						ctv.setIsPageLink("1");
						ctv.setIconCls("file");
						ctv.setLeaf(true);
						if(menuList.contains(ctv.getId())) {
							ctv.setChecked(true);
						}
						
						list.add(ctv);
					}
				}

				JSONArray json = new JSONArray();
				json = JSONArray.fromObject(list);
				resultStr = json.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return resultStr;
	}
	
	/**
	 * 插入权限
	 * @param jso
	 * @return
	 */
	public String insertMenu(String jso) {
		JSONObject jsobject = JSONObject.fromObject(jso);
		
		String roleid = jsobject.getString("roleid");
		
		if (roleid.startsWith("r_")) {
			roleid = roleid.substring(2);
		}
		
		String menuid = jsobject.getString("menuid");
		
		String[] ids = null;
		
		if (menuid.length() > 0) {
			ids = menuid.substring(0, menuid.length() - 1).split(",");
		}
		
		DAO dao = new DAO();
		
		try {
			deleteMenu(jso);
			for (int i = 0; ids != null && i < ids.length; i++) {
				String sql = "insert into app_purview values("
						+ roleid + "," + ids[i] + ", null)";
				dao.execCommand(ConstValue.DBNAME, sql);
			}
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "数据库操作失败";
		}
	}

	/**
	 * 删除权限
	 * @param jso
	 */
	public void deleteMenu(String jso) {
		JSONObject jsobject = JSONObject.fromObject(jso);
		String roleid = jsobject.getString("roleid");
		if (roleid.startsWith("r_")) {
			roleid = roleid.substring(2);
		}
		String sql = "delete from app_purview where uid =" + roleid;
		DAO dao = new DAO();
		try {
			dao.execCommand(ConstValue.DBNAME, sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean hasChild(String currentCode, String plCode)
	{
		String sql = "select * from cm_commlist where CL_PCODE='"+currentCode+"' and PL_CODE='" + plCode + "'";
		
		DAO dao = new DAO();
		
		try {
			Vector v = dao.getDataSet(ConstValue.DBNAME, sql);
			if (v == null) {
				sql = "select * from cm_commlist where CL_PCODE=-1 and PARM=" + currentCode;
				v = dao.getDataSet(ConstValue.DBNAME, sql);
			}
			
			if(v!=null && v.size()>0) {
				return true;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		return false;
	}
	
	private ArrayList getUserMenuList(String userID)
	{
		String sql = "select * from app_purview where UID='" + userID + "'";
		
		DAO dao = new DAO();
		
		ArrayList menuList = new ArrayList();
		
		try {
			Vector v = dao.getDataSet(ConstValue.DBNAME, sql);
			if(v!=null && v.size()>0) {
				for (int i=0; i<v.size(); i++) {
					Hashtable table = (Hashtable)v.get(i);
					menuList.add(table.get("MENUID"));
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		return menuList;
	}
}
